package httpclient

import (
	"encoding/json"
	"fmt"
)

// 微信 access_token 返回结构体
type responseAccessToken struct {
	ErrCode int32 			`json:"errcode"`
	ErrMsg string 			`json:"errmsg"`
	AccessToken string 		`json:"access_token"`
	ExpiresIn int32 		`json:"expires_in"`
	RefreshToken string 	`json:"refresh_token"`
	Openid string 			`json:"openid"`
	Scope string 			`json:"scope"`
	Unionid string 			`json:"unionid"`
}

// 微信 userinfo 返回结构体
type responseWxUserInfo struct {

}

// 获取微信token
func GetWxToken(appId, secret, code string) (*responseAccessToken, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", appId, secret, code);

	body, err := HttpGet(url)
	if err == nil {
		res := &responseAccessToken{}
		err = json.Unmarshal(body, res)
		if err == nil {
			return res, nil
		}
	}
	return nil, err
}

// 获取微信用户信息
func GetWxUserInfo(openId, token string) (*responseWxUserInfo, error) {
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?openid=%s&access_token=%s", openId, token);

	body, err := HttpGet(url)
	if err == nil {
		res := &responseWxUserInfo{}
		err = json.Unmarshal(body, res)
		if err == nil {
			return res, nil
		}
	}
	return nil, err
}